﻿using System;

namespace StackNamespace
{
    public class Stack
    {
        private int length;
        private StackItem lastItem;

        public Stack()
        {
            lastItem = null;
            length = 0;
        }
        public Object GetValue()
        {
            Object returnValue;
            if (length == 0)
            {
                throw new Exception("Stack is empty.");
            }
            else
            {
                returnValue = lastItem.GetValue();
                lastItem = lastItem.GetPrevItem();
                length--;
            }
            return returnValue;
        }
        public void AddValue(Object _value)
        {
            StackItem item = new StackItem(_value);
            if (length != 0)
            {
                item.SetPrevItem(lastItem);
            }
            else
            {
                item.SetPrevItem(null);
            }
            lastItem = item;
            length++;
        }
        public void Clear()
        {
            lastItem = null;
            length = 0;
        }
        public int GetLength()
        {
            return length;
        }
        public Object ReadValueByIndex(int index)
        {
            Object returnValue;
            if ((index > (length - 1)) || (index < 0))
            {
                throw new Exception("There is no element with this index.");
            }
            else
            {
                StackItem currentItem = lastItem;
                for (int i = 0; i < (length - index - 1); i++)
                {
                    currentItem = currentItem.GetPrevItem();
                }
                returnValue = currentItem.GetValue();
            }
            return returnValue;
        }
        public int SearchValue(Object searchValue)
        {
            int index = -1;
            StackItem item = lastItem;
            for (int i = (length-1); i >= 0; i--)
            {
                if (searchValue == item.GetValue())
                {
                    index = i;
                    break;
                }
                else
                {
                    item = item.GetPrevItem();
                }
            }
            return index;
        }
    }
}
